using System.Collections.ObjectModel;
using System.IO;
using FileTransferDesktop.Models;

namespace FileTransferDesktop.ViewModels.Dialogs;

public partial class UploadDialogViewModel : ObservableObject
{
    [ObservableProperty]
    private ObservableCollection<UploadFileItem> _fileItems = [];

    [ObservableProperty]
    private string _globalAdditionalInfo = string.Empty;

    [ObservableProperty]
    private UploadFileItem? _selectedFileItem;

    [ObservableProperty]
    private bool _dialogResult = false;

    // 新增属性用于界面绑定
    [ObservableProperty]
    private string _fileCountText = "暂无文件";

    [ObservableProperty]
    private string _statusText = "请选择要上传的文件";

    // 新增属性用于可见性控制
    [ObservableProperty]
    private bool _hasFiles = false;

    [ObservableProperty]
    private bool _hasNoFiles = true;

    public Action? OnConfirm { get; set; }
    public Action? RequestClose { get; set; }

    public UploadDialogViewModel()
    {
        // 监听文件列表变化
        FileItems.CollectionChanged += OnFileItemsChanged;
    }

    private void OnFileItemsChanged(
        object? sender,
        System.Collections.Specialized.NotifyCollectionChangedEventArgs e
    )
    {
        UpdateFileCountText();
        UpdateStatusText();
        UpdateVisibilityProperties();
        ConfirmCommand.NotifyCanExecuteChanged();
    }

    private void UpdateFileCountText()
    {
        var count = FileItems.Count;
        FileCountText =
            count == 0 ? "暂无文件"
            : count == 1 ? "1 个文件"
            : $"{count} 个文件";
    }

    private void UpdateStatusText()
    {
        var count = FileItems.Count;
        if (count == 0)
        {
            StatusText = "请选择要上传的文件";
        }
        else
        {
            var totalSize = FileItems.Sum(f => f.FileSize);
            var sizeText = FormatFileSize(totalSize);
            StatusText =
                count == 1
                    ? $"准备上传 1 个文件，总大小 {sizeText}"
                    : $"准备上传 {count} 个文件，总大小 {sizeText}";
        }
    }

    private void UpdateVisibilityProperties()
    {
        var count = FileItems.Count;
        HasFiles = count > 0;
        HasNoFiles = count == 0;
    }

    private static string FormatFileSize(double bytes)
    {
        string[] sizes = ["B", "KB", "MB", "GB", "TB"];
        int order = 0;
        while (bytes >= 1024 && order < sizes.Length - 1)
        {
            order++;
            bytes /= 1024;
        }
        return $"{bytes:0.##} {sizes[order]}";
    }

    [RelayCommand]
    private void AddFiles()
    {
        var openFileDialog = new OpenFileDialog
        {
            Title = "选择要上传的文件",
            Filter = "所有文件 (*.*)|*.*",
            Multiselect = true,
        };

        if (openFileDialog.ShowDialog() != true)
            return;
        foreach (var fileName in openFileDialog.FileNames)
        {
            if (FileItems.Any(f => f.FilePath.Equals(fileName, StringComparison.OrdinalIgnoreCase)))
                continue;

            var fileItem = new UploadFileItem(fileName);
            FileItems.Add(fileItem);
        }
    }

    /// <summary>
    /// 处理拖拽文件
    /// </summary>
    /// <param name="filePaths">拖拽的文件路径数组</param>
    public void AddDroppedFiles(string[] filePaths)
    {
        if (filePaths == null || filePaths.Length == 0)
            return;

        foreach (var filePath in filePaths)
        {
            try
            {
                // 检查文件是否存在
                if (!File.Exists(filePath))
                    continue;

                // 检查是否已经存在相同路径的文件
                if (
                    FileItems.Any(f =>
                        f.FilePath.Equals(filePath, StringComparison.OrdinalIgnoreCase)
                    )
                )
                    continue;

                var fileItem = new UploadFileItem(filePath);
                FileItems.Add(fileItem);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"添加拖拽文件失败: {ex.Message}");
            }
        }
    }

    [RelayCommand]
    private void RemoveFile(UploadFileItem? fileItem)
    {
        if (fileItem != null)
        {
            FileItems.Remove(fileItem);
        }
    }

    [RelayCommand]
    private void RemoveAllFiles()
    {
        FileItems.Clear();
    }

    public bool ConfirmButtonCanExecute => FileItems.Any();

    [RelayCommand(CanExecute = nameof(ConfirmButtonCanExecute))]
    private Task Confirm()
    {
        if (FileItems.Count == 0)
        {
            return Task.CompletedTask;
        }

        DialogResult = true;
        OnConfirm?.Invoke();
        RequestClose?.Invoke();
        return Task.CompletedTask;
    }

    [RelayCommand]
    private void Cancel()
    {
        DialogResult = false;
    }
}
